//package com.example.demo.interceptor;
//
//import com.example.demo.entity.Users;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.web.servlet.HandlerInterceptor;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//
//@Slf4j
//public class FirstInterceptor implements HandlerInterceptor {
//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
//        String userName = (String) request.getSession().getAttribute("userName");
//        if (userName!= null){
//            log.info("已通过验证");
//            response.setStatus(200);
//            return true;
//        }else {
//            log.info("请求已进入拦截器");
//            response.setStatus(500);
//            return false;
//        }
//    }
//}

package com.example.demo.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
public class FirstInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userName = (String) request.getSession().getAttribute("userName");
        if (userName != null) {
            log.info("已通过验证");
            response.setStatus(200);
            if (request.getRequestURI().startsWith("/admin/")) {
                String user = (String) request.getSession().getAttribute("userName");
                if (user != null && user.intern().contains("admin")) {
                    return true;
                } else {
                    log.info("请求被拦截，用户不是管理员");
                    response.setStatus(500);
                    return false;
                }
            } else {
                return true;
            }
        } else {
            log.info("请求已进入拦截器");
            response.setStatus(500);
            return false;
        }
    }
}

